package org.gary.admin.dao.impl;

import java.sql.SQLException;

import javax.annotation.Resource;

import org.gary.admin.dao.AdministratorDao;
import org.gary.admin.model.Administrator;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

/**
 * admin的dao类
 * @author Administrator
 *
 */
@Component("administratorDao")
public class AdministratorDaoImpl implements AdministratorDao {
	private HibernateTemplate hibernateTemplate;
	private String hql;//设定一个全局变量存放hql

	/* (non-Javadoc)
	 * @see org.gary.admin.dao.impl.AdministratorDao#login(java.lang.String, java.lang.String)
	 */
	public int login(String username, String password) {
		setHql("select count(*) from " + Administrator.class.getName()
				+ " admin where admin.username = '" + username
				+ "' and admin.password = '" + password + "'");
		Integer count = hibernateTemplate.execute(new HibernateCallback<Integer>() {

			@Override
			public Integer doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createQuery(getHql());
				return new Integer(q.uniqueResult().toString());
			}
		});
		return count;
	}

	/* (non-Javadoc)
	 * @see org.gary.admin.dao.impl.AdministratorDao#loadByUsername(java.lang.String)
	 */
	public Administrator loadByUsername(String username) {
		setHql("from " + Administrator.class.getName() + " admin where admin.username = '" + username + "'");
		Administrator admin = hibernateTemplate.execute(new HibernateCallback<Administrator>() {

			@Override
			public Administrator doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createQuery(getHql());
				return (Administrator) q.uniqueResult();
			}
		});
		return admin;
	}
	
	/* (non-Javadoc)
	 * @see org.gary.admin.dao.impl.AdministratorDao#checkUsernameExist(java.lang.String)
	 */
	public int checkUsernameExist(String username) {
		setHql("select count(*) from " + Administrator.class.getName() + " admin where admin.username = '" + username + "'");
		Integer count = hibernateTemplate.execute(new HibernateCallback<Integer>() {

			@Override
			public Integer doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createQuery(getHql());
				return new Integer(q.uniqueResult().toString());
			}
		});
		return count;
	}
	
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHql(String hql) {
		this.hql = hql;
	}

	public String getHql() {
		return hql;
	}
}
